import 'package:duqing/components/video_card.dart';
import 'package:duqing/models/video_model.dart';
import 'package:duqing/services/video_service.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class VideoPage extends StatefulWidget {
  const VideoPage({Key key}) : super(key: key);

  @override
  _VideoPageState createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage>
    with AutomaticKeepAliveClientMixin {
  EasyRefreshController _controller;
  int page = 1;
  int limit = 10;
  bool hasMore;

  List<VideoItem> _videoList = VideoList([]).list;

  Future _onLaod() {
    _getVideoList(push: true);
    _controller.finishLoad(noMore: !hasMore);
  }

  Future _onRefresh() {
    page = 1;
    _getVideoList();
    _controller.resetLoadState();
  }

  @override
  void dispose() {
    _controller.dispose();
  }

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController();
  }

  Future _getVideoList({bool push = false}) async {
    Map<String, dynamic> result = await VideoService.getVideos(page: page);
    VideoList videoListModel = VideoList.fromJson(result['data']);
    try {
      setState(() {
        hasMore = page * limit > result['total'];
        page++;
        if (push) {
          _videoList.addAll(videoListModel.list);
        } else {
          _videoList = videoListModel.list;
        }
      });
    } catch (e, s) {
      print(s);
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      firstRefresh: true,
      onLoad: _onLaod,
      onRefresh: _onRefresh,
      controller: _controller,
      child: ListView.builder(
          itemCount: _videoList.length,
          itemBuilder: (BuildContext context, int index) {
            return Column(
              children:[
                const SizedBox(height: 8,),
                VideoCard(
                  videoItem: _videoList[index],
                ),
              ],
            );
          }),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
